/*
 * Copyright(c) 2022 长沙市希尚网络科技有限公司
 * 注意：本内容仅限于长沙市希尚网络科技有限公司内部传阅，禁止外泄以及用于其他的商业目的
 */

package com.jubaozan.reward.modules.sharding;

import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.sharding.api.sharding.standard.PreciseShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.RangeShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.StandardShardingAlgorithm;

import java.util.Collection;
import java.util.Objects;

/**
 * 租户分表策略
 *
 * @author LiuLongXiang
 * @version 1.0 2024/11/9
 */
@Slf4j
public class ShardingTableByTenantIdAlgorithm implements StandardShardingAlgorithm<Long> {

    @Override
    public String doSharding(Collection<String> collection, PreciseShardingValue<Long> preciseShardingValue) {
        boolean isSharding = true;
        Long tenantId = preciseShardingValue.getValue();
        ShardingConfiguration instance = ShardingConfiguration.getInstance();
        if (Objects.nonNull(instance) && instance.getTenantIds().contains(tenantId)) {
            isSharding = false;
        }

        String tableName = preciseShardingValue.getLogicTableName();
        if (isSharding) {
            tableName = tableName + '_' + tenantId;
        }

        logger.debug("Current table selected : [{}]", tableName);
        return tableName;
    }

    @Override
    public Collection<String> doSharding(Collection<String> collection, RangeShardingValue<Long> rangeShardingValue) {
        return null;
    }

    @Override
    public String getType() {
        return null;
    }


    @Override
    public void init() {

    }
}
